#!/bin/bash

# 构建脚本
# 使用方法: ./build.sh [debug|release|clean]

set -e  # 遇到错误时退出

PROJECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BUILD_DIR="${PROJECT_DIR}/build"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 打印函数
print_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 清理构建目录
clean_build() {
    print_info "清理构建目录..."
    if [ -d "$BUILD_DIR" ]; then
        rm -rf "$BUILD_DIR"
        print_info "构建目录已清理"
    else
        print_info "构建目录不存在，无需清理"
    fi
}

# 配置CMake
configure_cmake() {
    local build_type=$1
    print_info "配置CMake (构建类型: $build_type)..."
    
    mkdir -p "$BUILD_DIR"
    cd "$BUILD_DIR"
    
    cmake -DCMAKE_BUILD_TYPE="$build_type" \
          -DCMAKE_EXPORT_COMPILE_COMMANDS=ON \
          "$PROJECT_DIR"
    
    print_info "CMake配置完成"
}

# 编译项目
build_project() {
    print_info "开始编译..."
    cd "$BUILD_DIR"
    
    # 获取CPU核心数
    local cores=$(nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || echo "4")
    
    make -j"$cores"
    
    print_info "编译完成"
    print_info "可执行文件位置: $BUILD_DIR/bin/CoroutineTest"
}

# 运行项目
run_project() {
    print_info "运行项目..."
    cd "$BUILD_DIR"
    ./bin/CoroutineTest
}

# 主函数
main() {
    local action=${1:-debug}
    
    case $action in
        "debug")
            print_info "开始Debug构建..."
            clean_build
            configure_cmake "Debug"
            build_project
            run_project
            ;;
        "release")
            print_info "开始Release构建..."
            clean_build
            configure_cmake "Release"
            build_project
            run_project
            ;;
        "clean")
            clean_build
            ;;
        "run")
            if [ ! -f "$BUILD_DIR/bin/CoroutineTest" ]; then
                print_error "可执行文件不存在，请先构建项目"
                exit 1
            fi
            run_project
            ;;
        *)
            print_error "未知参数: $action"
            echo "使用方法: $0 [debug|release|clean|run]"
            echo "  debug   - Debug构建并运行 (默认)"
            echo "  release - Release构建并运行"
            echo "  clean   - 清理构建目录"
            echo "  run     - 运行已构建的项目"
            exit 1
            ;;
    esac
}

# 检查依赖
check_dependencies() {
    if ! command -v cmake &> /dev/null; then
        print_error "CMake未安装，请先安装CMake"
        exit 1
    fi
    
    if ! command -v make &> /dev/null; then
        print_error "Make未安装，请先安装Make"
        exit 1
    fi
}

# 执行
check_dependencies
main "$@"
